package project.dwd.wit.ie.tripfinancemanager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import project.dwd.wit.ie.tripfinancemanager.model.Trip;


public class ExpensesActivity extends ActionBarActivity {

    private String[] costsTrip;
    private ListView listViewExpenses;

    private String tripName = "";
    private String filename = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expenses);

        //Getting data from previous Activity...
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            filename = extras.getString("filename");
            tripName = extras.getString("tripName");
        }

        TextView tripNameTextView = (TextView) findViewById(R.id.trip_name_textview);
        tripNameTextView.setText(tripName);

        listViewExpenses = (ListView) findViewById(R.id.list_expenses_listview);

        openFile(filename);
    }

    public void openFile(String filename) {
        new ReadFile(this).execute(filename);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_expenses, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void addNewExpense(View view) {
        Intent i = new Intent(this, NewExpenseActivity.class);
        i.putExtra("filename", this.filename);
        i.putExtra("tripName", this.tripName);
        startActivity(i);
    }

    public void updateGui(String[] items) {
        ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, items);

        listViewExpenses.setAdapter(adapter);
        listViewExpenses.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item value
                String  itemValue = (String) listViewExpenses.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :" + position + "  ListItem : " + itemValue, Toast.LENGTH_LONG)
                        .show();
            }

        });
    }


    public class ReadFile extends AsyncTask<String, Void, String[]> {

        private Activity activity;
        private ProgressDialog dialog;

        public ReadFile(Activity activity) {
            this.activity = activity;
            dialog = new ProgressDialog(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            this.dialog.setMessage("Loading file... please wait");
            this.dialog.show();
            Log.e("onPre", "onPreExecute Method called");
        }

        @Override
        protected String[] doInBackground(String... params) {
            return readFile(params[0]);
        }

        public String[] readFile(String filename) {
            String tripName = "";
            //Get the text file
            File file = new File(getCacheDir(),filename);
            //Read text from file
            StringBuilder text = new StringBuilder();
            String expenses = "";

            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                //First Line is a Trip Name
                tripName = br.readLine();
                Log.e("TripName AQUIIII... ", tripName);

                while ((line = br.readLine()) != null) {
                    expenses = expenses + line + "--";
                }

                costsTrip = expenses.split("--");
                br.close();
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }

            Trip _aTrip = new Trip(filename, tripName, text);
            Log.e("_aTrip variable", _aTrip.toString());
            return costsTrip;
        }

        @Override
        protected void onPostExecute(String[] result) {
            super.onPostExecute(result);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            updateGui(result);
        }
    }

}


